package lk.icta.common.service.impl;

import lk.icta.common.ELandRuntimeException;
import lk.icta.common.dao.ContactsDAO;
import lk.icta.common.entity.Contacts;
import lk.icta.common.service.ContactsManager;
import lk.icta.user.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Supun Nimesh Karunathilaka
 */
public class ContactsManagerImpl implements ContactsManager {

    private static final Logger logger = LoggerFactory.getLogger(ContactsManagerImpl.class);

    private final ContactsDAO contactsDAO;

    public ContactsManagerImpl(ContactsDAO contactsDAO) {
        this.contactsDAO = contactsDAO;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void addContact(Contacts contact, User user) {
        contactsDAO.addContacts(contact, user);
        logger.info("Added contact information");
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void updateContact(Contacts contacts, User user) {
        contactsDAO.updateContacts(contacts, user);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void deleteContact(Contacts contacts, User user) {
        logger.debug("Delete the contact {} by {}", contacts.getId(), user.getUsername());
        contactsDAO.deleteContact(contacts, user);
    }

    @Transactional(propagation = Propagation.NEVER, readOnly = true)
    public Contacts getContactsByIdUKey(long id, User user) {
        logger.debug("get contact by contact id  {} ", id);
        return contactsDAO.getContactsByIdUKey(id, user);
    }

    @Transactional(propagation = Propagation.NEVER, readOnly = true)
    public List<Contacts> getAllContacts() {
        return contactsDAO.findAll();
    }

    private void handleELandRuntimeException(String message, int code) {
        logger.error(message);
        throw new ELandRuntimeException(message, code);
    }
}
